﻿using KinonekoSoftware.CodariaDB.Documents.Timelines;

namespace KinonekoSoftware.Studio.Pages.Theories
{
    public sealed class NewEpochViewModel : ObjectDialog<Epoch>
    {

        public static Task<Result<Epoch>> Create()
        {
            return Dialog<Epoch>(new NewEpochViewModel());
        }

        public static Task<Result<Epoch>> Edit(Epoch target)
        {
            var context = new DialogContext();
            context.Set(ContextBase.Key_Value, target);
            return Dialog<Epoch>(new NewEpochViewModel(), context);
        }

        private string         _name;
        private string         _color;
        private Epoch _target;

        protected override void CreateValidationRules(ICollection<DialogRule> rules)
        {
            rules.Add(DialogRule.Create<NewEpochViewModel>(CodariaSR.Text_Parameter_EmptyName, x => !string.IsNullOrEmpty(x.Name)));
        }

        protected override bool OnReceive(DialogContext context)
        {
            if (context.Has(ContextBase.Key_Value))
            {
                _target = context.GetObject<Epoch>(ContextBase.Key_Value);
                Name    = _target.Name;
                Color   = _target.Color;
                return true;
            }

            return false;
        }

        protected override Epoch OnFinish(bool editing)
        {
            if (editing)
            {
                _target.Color = Color;
                _target.Name  = Name;
            }
            else
            {
                _target = new Epoch
                {
                    Id    = ID.Get(),
                    Color = Color,
                    Name  = Name,
                };
            }

            return _target;
        }


        public string Color
        {
            get => _color;
            set => TryFinishAndSetValue(ref _color, value);
        }

        public string Name
        {
            get => _name;
            set => TryFinishAndSetValue(ref _name, value);
        }
    }
}